package com.customization.qs.download.web;

import com.alibaba.fastjson.JSONObject;
import com.customization.qs.download.service.SpecialWorkflowBatchDownloadService;
import com.customization.qs.download.service.impl.SpecialWorkflowBatchDownloadServiceImpl;
import com.engine.common.util.ServiceUtil;
import org.apache.commons.lang.StringUtils;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import java.io.IOException;
import java.io.InputStream;

public class SpecialWorkflowBatchDownloadAction {

    private static final Logger log = LoggerFactory.getLogger(SpecialWorkflowBatchDownloadAction.class);

    private SpecialWorkflowBatchDownloadService getService(User user) {
        return ServiceUtil.getService(SpecialWorkflowBatchDownloadServiceImpl.class, user);
    }

    @POST
    @Path("/workflow/batch/download")
    public String batchDownload(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        JSONObject result = new JSONObject();
        try {
            result.put("msg", "下载成功！");
            result.put("data", null);
            result.put("code", 200);
            result.put("errorCode", 1);

            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);

            String body = readBodyUTF8(request);
            log.info("请求体参数：" + body);
            if (body != null) {
                JSONObject parseJson = JSONObject.parseObject(body);
                String nodeId = parseJson.getString("nodeId");
                String workflowId = parseJson.getString("workflowId");
                String requestId = parseJson.getString("requestId");
                log.info("nodeId：" + nodeId + ",workflowId：" + workflowId + ",requestId：" + requestId);
                if (StringUtils.isNotBlank(nodeId) && StringUtils.isNotBlank(workflowId)) {
                    JSONObject fileInfo = getService(user).batchDownloadFile(workflowId, requestId, nodeId, request, response);
                    if(fileInfo != null){
                        result.put("data", fileInfo);
                    }else {
                        result.put("msg", "文件为空，请联系管理员！");
                        result.put("code", 500);
                        result.put("errorCode", 10003);
                    }
                } else {
                    result.put("msg", "参数异常，请检查参数！");
                    result.put("code", 500);
                    result.put("errorCode", 10003);
                }
            }else {
                result.put("msg", "参数异常，请检查参数！");
                result.put("code", 500);
                result.put("errorCode", 10003);
            }
        } catch (Exception e) {
            log.info("文件下载异常：" + e.getMessage());
            result.put("msg", e.getMessage());
            result.put("code", 500);
            result.put("errorCode", 5000);
        }
        return JSONObject.toJSONString(result);

    }

    /**
     * 获取HttpServletRequest中请求体
     * @param request
     * @return
     * @throws IOException
     */
    public static String readBodyUTF8(HttpServletRequest request) {
        if ("POST".equals(request.getMethod())) {
            InputStream is = null;
            try {
                is = request.getInputStream();
                StringBuilder sb = new StringBuilder();
                byte[] b = new byte[4096];
                for (int n; (n = is.read(b)) != -1; ) {
                    sb.append(new String(b, 0, n, "utf-8"));
                }
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

}
